package com.tbb.app.base.controller;

import com.alibaba.fastjson.JSON;
import com.tbb.app.base.entity.User;
import com.tbb.app.base.service.IMessageService;
import com.tbb.app.base.service.IUserService;
import com.tbb.app.base.vo.MessageVO;
import com.tbb.app.common.exception.BusinessException;
import com.tbb.app.common.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/message/{sendId}/{receiveId}")
@Component
@Slf4j
//@CrossOrigin(origins = "*")
public class MessageEndpoint {

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static final ConcurrentHashMap<String, MessageEndpoint> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * userId
     */
    private String sendId;
    /**
     * userAccount
     */
    private String sendAccount;
    /**
     * userName
     */
    private String sendName;
    /**
     * receiveId
     */
    private String receiveId;

    /**
     * 点对点聊天
     */
    public static void sendMessage(MessageVO vo) throws IOException {
        if (webSocketMap.containsKey(vo.getReceiveId() + vo.getSendId())) {
            String message = JSON.toJSONString(vo);
            webSocketMap.get(vo.getReceiveId() + vo.getSendId()).sendMessage(message);
        }
    }

    public static synchronized void addOnlineCount() {
        onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        onlineCount--;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sendId") String sendId, @PathParam("receiveId") String receiveId) {
        try {
            IUserService iUserService = SpringContextUtil.getBean(IUserService.class);
            User user = iUserService.getById(sendId);
            if (user != null) {
                this.session = session;
                this.sendId = user.getId();
                this.sendName = user.getName();
                this.sendAccount = user.getAccount();
                this.receiveId = receiveId;
                MessageEndpoint me = webSocketMap.get(this.sendId + this.receiveId);
                if (me == null) {
                    addOnlineCount();
                }
                webSocketMap.put(this.sendId + this.receiveId, this);
                log.info("[{}] join, total online [{}]", this.sendName + "." + this.sendAccount + "." + this.receiveId, onlineCount);
            } else {
                session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "错误的token"));
            }
        } catch (BusinessException | IOException e) {
            log.error("WebSocket connect failed", e);
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(this.sendId + this.receiveId)) {
            webSocketMap.remove(this.sendId + this.receiveId);
            subOnlineCount();
            log.info("[{}] out, total online [{}]", this.sendName + "." + this.sendAccount + "." + this.receiveId, onlineCount);
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("[{}] message [{}]", this.sendName + "." + this.sendAccount + "." + this.receiveId, message);
        MessageVO vo = new MessageVO();
        vo.setText(message);
        vo.setSendId(this.sendId);
        vo.setReceiveId(this.receiveId);
        IMessageService iMessageService = SpringContextUtil.getBean(IMessageService.class);
        iMessageService.sendMessage(vo);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket connect error", error);
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
}
